package com.example.zhinongbao.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.example.zhinongbao.Model.PersonalCenterImpl;
import com.example.zhinongbao.R;
import com.example.zhinongbao.contract.PersonalCenterContact;
import com.example.zhinongbao.presenter.PersonalCenterPresenter;
import com.google.android.material.bottomsheet.BottomSheetDialog;

public class PersonalCenter extends AppCompatActivity implements PersonalCenterContact {


    private static final int PICK_IMAGE_REQUEST = 1;
    private BottomSheetDialog bottomSheetDialog;
    private ImageButton BackBtn;
    private ImageView ShowConcern;
    private LinearLayout EditConcern, EditUserName, EditAge, EditAddress, EditPhone, Edit_user_id;
    private TextView ShowName, ShowPhone, ShowAge, ShowLocal, ShowUser_id;

    private PersonalCenterPresenter personalCenterPresenter;
    private SharedPreferences mSharedPreferences;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center);
        BackBtn = findViewById(R.id.personal_back_btn);
        EditConcern = findViewById(R.id.edit_concern_btn);
//        EditUserName = findViewById(R.id.edit_userName);
        EditAge = findViewById(R.id.edit_userAge);
        EditAddress = findViewById(R.id.edit_userLocal);
        EditPhone = findViewById(R.id.edit_phone);
        Edit_user_id = findViewById(R.id.edit_user_id);
        ShowUser_id = findViewById(R.id.personal_center_show_user_id);
        ShowName = findViewById(R.id.personal_center_show_userName);
        ShowPhone = findViewById(R.id.personal_center_show_phone);
        ShowAge = findViewById(R.id.personal_center_show_age);
        ShowLocal = findViewById(R.id.personal_center_show_local);
        ShowConcern = findViewById(R.id.edit_concern_img);
//        userInfoDao = new UserInfoDao(this);

        //设置头像
        EditConcern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        });


        BackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        Edit_user_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateID();
            }
        });
        EditAge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateAge();
            }
        });
        EditAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateAddress();
            }
        });
        EditPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdatePhone();
            }
        });


        PersonalCenterImpl personalCenter = new PersonalCenterImpl(this);
        personalCenterPresenter = new PersonalCenterPresenter(this, personalCenter);
        mSharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        String User_id = mSharedPreferences.getString("username", "");
        String username =mSharedPreferences.getString("username","");
        Log.d("sp", "get username = " + User_id);
        Log.d("sp", "get username------ = " + username);
        ShowUser_id.setText(User_id);
        ShowName.setText(username);
        personalCenterPresenter.showMessage(User_id);
        personalCenterPresenter.showMessage(username);
    }

    //获取图片路径
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = selectedImageUri.toString();

            SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            String user_id = sharedPreferences.getString("username", "");
            personalCenterPresenter.updateAvatar(user_id, imagePath);

            Uri uri = Uri.parse(imagePath);
            ShowConcern.setImageURI(uri);
        }
    }

    // 通过Uri获取图片路径
    private String getPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(columnIndex);
            cursor.close();
            return path;
        }
        return uri.getPath(); // 如果获取不到，则直接返回Uri的路径

    }


    private void showBottomSheetUpdateID() {
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_id);
        EditText UpdateId = bottomSheetDialog.findViewById(R.id.update_input_name);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_name_cancel);
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_name_btn);

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                String username = sharedPreferences.getString("username", "");
                String newuser_id = UpdateId.getText().toString();
                Log.d("sp", "get newuser_id = " + newuser_id);
                ShowUser_id.setText(newuser_id);
                personalCenterPresenter.updateID(username, newuser_id);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newuser_id, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }

    private void showBottomSheetUpdateAge() {
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_age);
        EditText UpdateAge = bottomSheetDialog.findViewById(R.id.update_input_age);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_age_cancel);
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_age_btn);

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                String username = sharedPreferences.getString("username", "");
                String newAge = UpdateAge.getText().toString();
                ShowAge.setText(newAge);
                personalCenterPresenter.updateAge(username, "" + newAge);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newAge, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }

    private void showBottomSheetUpdateAddress() {
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_local);
        EditText UpdateAddress = bottomSheetDialog.findViewById(R.id.update_input_local);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_local_cancel);
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_local_btn);

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                String username = sharedPreferences.getString("username", "");
                String newAddress = UpdateAddress.getText().toString();
                ShowLocal.setText(newAddress);
                personalCenterPresenter.updateAddress(username, newAddress);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newAddress, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }

    private void showBottomSheetUpdatePhone() {
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_phone);
        EditText UpdatePhone = bottomSheetDialog.findViewById(R.id.update_input_phone);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_phone_cancel);
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_phone_btn);

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                String username = sharedPreferences.getString("username", "");
                String newPhone = UpdatePhone.getText().toString();
                Log.d("sp", "get newPhone = " + newPhone);
                ShowPhone.setText(newPhone);
                personalCenterPresenter.updatePhone(username, newPhone);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newPhone, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }



    @Override
    public void updateAvatar(String avatarPath) {
        //Toast.makeText(this, avatarPath, Toast.LENGTH_SHORT).show();
        Uri uri = Uri.parse(avatarPath);
        ImageView imageView = findViewById(R.id.edit_concern_img);
        // 或者使用原生方法加载
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    final Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//                    imageView.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            imageView.setImageBitmap(bitmap);
//                        }
//                    });
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    // 处理解析图片时的异常
//                }
//            }
//        }).start();
    }


    @Override
    public void updateID(String user_id) {
        Log.d("sp", "get user_id = " + user_id);
        ShowUser_id.setText(user_id);
    }

    @Override
    public void updateAge(String age) {
        ShowAge.setText(age);
    }

    @Override
    public void updateAddress(String address) {
        ShowLocal.setText(address);
    }

    @Override
    public void updatePhone(String phone) {
        ShowPhone.setText(phone);
    }

    @Override
    public void updateName(String username) {
        ShowName.setText(username);
    }
}